<template>
  <el-dialog :title="isEdit?'修改用户':'新增用户'"  :visible.sync="visible"
             @close="$emit('update:show', false)">
    <el-form label-width="80px" :rules="rules" :model="params" ref="editForm" size="small">
      <Divider>基础信息</Divider>
      <div class="form-inline-2">
        <el-form-item label="登录账号" prop="username" v-if="hasPerm('user-sensitive-edit')||!isEdit">
          <el-input placeholder="请输入登录账号" v-model="params.username">
          </el-input>
        </el-form-item>
        <el-form-item label="登录账号" v-else>
          {{params.username}}
        </el-form-item>
        <el-form-item label="登录密码" prop="password" :rules="isEdit?rules.password2:rules.password"
                      v-if="hasPerm('user-sensitive-edit')||!isEdit">
          <el-input :placeholder="isEdit?'不想改密码请留空！':'请输入密码'" type="password" v-model="params.password"></el-input>
        </el-form-item>
        <el-form-item label="登录密码"v-else>
          <span class="text-danger">无权限不能修改</span>
        </el-form-item>
        <el-form-item label="用户姓名" prop="name">
          <el-input placeholder="请输入用户姓名" v-model="params.name"></el-input>
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input placeholder="请输入身份证号" v-model="params.idcard"></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input placeholder="请输入手机号码" v-model="params.phone"></el-input>
        </el-form-item>
      </div>
      <div class="vertical-line"></div>
      <div class="form-inline-2">
        <el-form-item label="警号" prop="policeNum">
          <el-input placeholder="请输入警号" v-model="params.policeNum"></el-input>
        </el-form-item>
        <el-form-item label="现任单位" prop="currentOrg">
          <org v-model="params.currentOrg"></org>
        </el-form-item>
        <el-form-item label="临时单位">
          <org v-model="params.temporaryOrg"></org>
        </el-form-item>
        <el-form-item label="警种">
          <police-type v-model="params.policeCode" :multiple="true"></police-type>
        </el-form-item>
        <el-form-item label="职位">
          <position v-model="params.positionCode" :multiple="true"></position>
        </el-form-item>
      </div>

      <div class="form-inline-2">
        <Divider>角色</Divider>
        <el-card shadow="never" style="height: 190px;">
          <role-tree v-model="params.roleId"></role-tree>
        </el-card>
      </div>
      <div class="vertical-line" style="border: 0;"></div>
      <div class="form-inline-2">
        <Divider>个人权限</Divider>
        <el-card shadow="never" style="height: 190px;">
          <permission-tree v-model="params.resourcesId"></permission-tree>
        </el-card>
      </div>
      <Divider></Divider>
      <el-form-item label="状态">
        <el-switch
          v-model="params.state"
          active-color="#13ce66"
          inactive-color="#ff4949"
          :active-value = '1'
          :inactive-value = '0'
          active-text="启用">
        </el-switch>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="saveEdit">保 存</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import PoliceType from '../../common/PoliceTypeSelect.vue'
  import Position from '../../common/PositionSelect.vue'
  import Org from '../../common/OrgSelect.vue'
  import {Divider} from 'iview'
  import PermissionTree from '../../common/PermissionTree'
  import RoleTree from '../../common/RoleTree'

  export default {
    name: "AddEditUserDialog",
    components: {
      PoliceType,
      Position,
      Org,
      Divider,
      PermissionTree,
      RoleTree
    },
    props: {
      show: {
        type: Boolean,
        default: false
      },
      userData: null
    },
    watch: {
      show () {
        this.visible = this.show;
      },
      userData: {
        handler() {
          if(this.userData){
            for(let k in this.params){
              this.params[k] = this.userData[k]?this.userData[k]:null;
              this.oldParams[k] = this.userData[k]?this.userData[k]:null;
            }
            this.params.password = '';
            this.params.policeCode = [];
            this.params.positionCode = [];
            this.params.roleId = [];
            this.params.resourcesId = [];
            this.userData.policeTypes.forEach((item) => {
              this.params.policeCode.push(item.code);
            });
            this.userData.positions.forEach((item) => {
              this.params.positionCode.push(item.code);
            });
            this.userData.roles.forEach((item) => {
              this.params.roleId.push(item.id);
            });
            this.userData.otherResources.forEach((item) => {
              this.params.resourcesId.push(item.id);
            });
            this.isEdit = true;
            //显示标题的值
              if(this.isEdit){
                this.title = '修改用户';
              }else{
                this.title = '新增用户';
              }
          }else{
            for(let k in this.params){
              this.params[k] = '';
            }
            this.params.policeCode = [];
            this.params.positionCode = [];
            this.params.roleId = [];
            this.params.resourcesId = [];
            this.params.state = 1;
            this.isEdit = false;
          }
        },
        immediate: true,
        deep: true
      }
    }
    ,
    data() {
      let usernameValid = (rule, value, callback) => {
        if (value && value.trim().length > 0 && value!==this.oldParams.username) {
          let params = {
            'username': value
          }
          this.api.post('/bucket-system/system/user/isexist', params)
            .then(function (response) {
              if (response.data===true) {
                callback('该用户名已经存在，请重新填写')
              } else if(response.data===false) {
                callback()
              } else {
                callback(new Error('服务端校验异常'))
              }
            })
            .catch(function () {
              callback(new Error('服务端校验异常'))
            })
        } else {
          callback()
        }
      };
      let policenumValid = (rule, value, callback) => {
        if (value && value.trim().length > 0 && value!==this.oldParams.policenum) {
          let params = {
            'policeNum': value
          }
          this.api.post('/bucket-system/system/user/isexist', params)
            .then(function (response) {
              if (response.data===true) {
                callback('该警号已经存在，请重新填写')
              } else if(response.data===false) {
                callback()
              } else {
                callback(new Error('服务端校验异常'))
              }
            })
            .catch(function () {
              callback(new Error('服务端校验异常'))
            })
        } else {
          callback()
        }
      };
      return {
        visible: this.show,
        isEdit: false,
        params: {
          id: '',
          name: '',
          username: '',
          password: '',
          idcard: '',
          phone: '',
          currentOrg: '',
          temporaryOrg: '',
          orgname: '',
          policeNum: '',
          policeCode: [],
          positionCode: [],
          roleId: [],
          resourcesId: [],
          title : '',
          state: 1
        },
        oldParams: {},
        rules: {
          username: [
            {required: true, message: '用户名不能为空', trigger: 'blur'},
            {validator: usernameValid, trigger: 'blur'}
          ],
          name: [
            {required: true, message: '姓名不能为空', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '密码不能为空', trigger: 'blur'}
          ],
          currentOrg: [
            {required: true, message: '未选择所属单位', trigger: 'blur'}
          ],
          password2: [
            {required: false, trigger: 'blur'}
          ],
          // policeNum: [
          //   {validator: policenumValid, trigger: 'blur'}
          // ]
        }
      }
    },
    methods: {
      saveEdit: function(){
        this.$refs['editForm'].validate((valid) => {
          if (valid) {
            let _url = '';
            if(!this.isEdit){
              _url = '/bucket-system/system/user/add';
            }else{
              _url = '/bucket-system/system/user/update';
            }
            if(this.oldParams && !this.params.password){
              this.params.password = this.oldParams.password;
            }
            this.api.post(_url, this.params)
              .then((data) => {
                if(data.code===200){
                  this.visible=false;
                  this.$message({
                    message: '保存成功',
                    type: 'success'
                  });
                  this.$parent.query();
                }else{
                  this.$message.error(data.data);
                }
              });
          } else {
            return false;
          }
        });
      }
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss">
  .ivu-divider-horizontal,.ivu-divider-horizontal.ivu-divider-with-text-center,
  .ivu-divider-horizontal.ivu-divider-with-text-left,
  .ivu-divider-horizontal.ivu-divider-with-text-right{
    margin: 0 0;
  }
  .el-card__body{
    padding: 0;
  }
</style>
<style scoped>
  .form-inline-2{
    display: inline-block;
    width: 46%;
  }
  .vertical-line{
    display: inline-block;
    width: 1px;
    height: 215px;
    border: 0.5px dashed #e8eaec;
    position: relative;
    margin: 0 10px;
  }
</style>
